<?php
namespace app\common\service;

use app\common\utils\ErrorCode;
use app\common\utils\Massage;
use app\common\utils\Res;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;




use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;

class FrontJwtService
{
    protected static $key = 'Mmc@Tsg#888+^2024%' . "dddd";

    public function __construct()
    {
        $this->key = md5($this->key);
    }

    public static function createToken($data, &$expireTime = 0)
    {
        $iatTime = time();
        $expireTime = $iatTime + $expireTime + 86400;//设置过期时间为1天
        $token = [
            "iss" => 'MmcLive2024',
            "aud" => '',
            "iat" => $iatTime,
            "nbf" => $iatTime + 3,
            "exp" => $expireTime,
            "data" => $data,
        ];
        $jwt = JWT::encode($token, self::$key, "HS256");
        return $jwt;
    }

    public static function createApiToken($data)
    {
        $token = [
            "iss" => 'MmcLive2024',
            "aud" => '',
            "iat" => time(),
            "nbf" => time() + 3,
            "exp" => time() + 1296000, //设置过期时间为15天
            "data" => json_encode($data),
        ];
        $jwt = JWT::encode($token, self::$key, "HS256");
        return $jwt;
    }

    public static function checkToken($token)
    {
        try {
            JWT::$leeway = 60; //当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, self::$key, array('HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array) $decoded;
            $arr['code'] = ErrorCode::SUCCESS;
            $arr['data'] = (array) ($arr['data']);
            if (empty($arr['data'])) {
                return Res::tokenError(Massage::TOKENERROR);
            }
            return $arr;

        } catch (SignatureInvalidException $e) {
            return Res::tokenError(Massage::TOKENERROR);
        } catch (BeforeValidException $beforeValidException) {
            return Res::tokenError(Massage::TOKENDEFALU);
        } catch (ExpiredException $expiredException) {
            return Res::tokenError(Massage::TOKENNOWTIME);
        } catch (\Exception $exception) {
            return Res::tokenError(Massage::TOKENNULL);
        }
    }
}
